/************************************************************************

								Heroes IV
					  Copyright 2000, The 3DO Company

	------------------------------------------------------------------
  						 adv_object_model_cache.cpp

	$Header: /heroes4/adv_object_model_cache.cpp $

	$NoKeywords: $

 ************************************************************************/

#include "precompiled.h"
#pragma warning( disable: 4786 ) // Disable the ever so helpful "identifier was truncated to '255' characters" warning

#include "adv_object_model_cache.h"

#include <map>
#include <utility>

#include "conversion_cache.h"
#include "pixel_24.h"
#include "resource_dir.h"
#include "shared_ptr.h"
#include "string_insensitive_compare.h"

// --------------------------------------------------------
// Unnamed namespace
// --------------------------------------------------------

namespace
{
	// --------------------------------------------------------
	// --------------------------------------------------------
	typedef t_conversion_cache< t_adv_object_model_24, t_adv_object_model > t_cache;
	typedef std::map< std::string, t_cache, t_string_insensitive_less > t_cache_map;

	// --------------------------------------------------------
	// --------------------------------------------------------
	t_cache_map & get_cache_map()
	{
		static t_cache_map cache_map;
		return cache_map;
	}


} // Unnamed namespace

// --------------------------------------------------------
// Load the adventure object model with the specified name
// --------------------------------------------------------
t_resource_cache< t_adv_object_model > get_adv_object_model_cache( std::string const& name )
{
	static std::string const k_prefix = t_resource_traits< t_adv_object_model_24 >::prefix;
	static std::string const k_extension = ".h4d";

	t_cache_map &			cache_map = get_cache_map();
	std::string				model_name;
	t_cache_map::iterator	map_iter;
	
	model_name = k_prefix;
	model_name += '.';
	model_name += name;
	model_name += k_extension;
	map_iter = cache_map.find( model_name );

	// search for model in map
	if ( map_iter == cache_map.end() )
	{
		// construct a cache and check if it's an alias
		t_cache		cache( name );
		std::string real_model_name = cache.get_name();

		if ( string_insensitive_compare( model_name, real_model_name ) == 0 )
			model_name = real_model_name; // force to point to same string
		else
		{	// if the model is an alias, check if the real object is in the map
			map_iter = cache_map.find( real_model_name );
			if (map_iter == cache_map.end())
			{	// if not, create it
				map_iter = cache_map.insert( std::make_pair( real_model_name, cache ) ).first;
			}
			else
			{
				cache = map_iter->second;
			}
		}
		map_iter = cache_map.insert( std::make_pair( model_name, cache ) ).first;
	}
	return map_iter->second;
}
